package com.angel.kuaidi.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;

import com.angel.kuaidi.utils.StringUtils;
import com.angel.kuaidi.utils.UtilsLog;

public class AgentHttpClient extends IAgentRequest {

	/** 最大连接数 */
	private static final int MAX_TOTAL_CONNECTION = 100;
	/** 每个路由最大连接数 */
	private final static int MAX_ROUTE_CONNECTIONS = 20;

	/** 连接池获取连接的最大等待时间 */
	private final static int DEFAULT_WAIT_TIMEOUT = 10000;
	/** 设置连接超时时间 */
	private static final int DEFAULT_CONN_TIMEOUT = 10000;
	/** socket读取数据超时时间 */
	private static final int DEFAULT_READ_TIMEOUT = 20000;
	/** 加密字符串 */
	private static final String MD5_CONSTANT = "soufunhttp";

	private static DefaultHttpClient mHttpClient;
	private static ThreadSafeClientConnManager mConnManager;

	private HttpRequestBase mHttpRequest;
	private HttpResponse mHttpResponse;

	private InputStream mEntityInputStream;
	private AgentInputStream mInputStream;

	private RequestEntity mRequestEntity;

	static {
		// Create and initialize HTTP parameters
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		// 设置最大连接数
		ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTION);
		// 设置每个路由最大连接数
		ConnPerRouteBean connPerRouteBean = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS);
		// 对localhost:80增加最大连接到50
		HttpHost localhost = new HttpHost("locahost", 80);
		connPerRouteBean.setMaxForRoute(new HttpRoute(localhost), 50);
		ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS));
		// 设置从连接池获取连接的最大等待时间
		ConnManagerParams.setTimeout(params, DEFAULT_WAIT_TIMEOUT);
		// 设置连接超时时间
		HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONN_TIMEOUT);
		// 设置socket读取数据超时时间
		HttpConnectionParams.setSoTimeout(params, DEFAULT_READ_TIMEOUT);
		// 设置以Socket 缓存大小
		HttpConnectionParams.setSocketBufferSize(params, 8192);
		// 设置重定向，缺省为 true , 这里设置成不重定向
		HttpClientParams.setRedirecting(params, false);

		// Create and initialize scheme registry
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

		// Create an HttpClient with the ThreadSafeClientConnManager.
		// This connection manager must be used if more than one thread will
		// be using the HttpClient.
		mConnManager = new ThreadSafeClientConnManager(params, schemeRegistry);
		mHttpClient = new DefaultHttpClient(mConnManager, params);

		mHttpClient.addRequestInterceptor(new HttpRequestInterceptor() {
			public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
				if (!request.containsHeader(HttpHeader.REQ.ACCEPT_ENCODING)) {
					request.addHeader(HttpHeader.REQ.ACCEPT_ENCODING, "gzip");
				}
			}
		});

		mHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {
			public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
				HttpEntity entity = response.getEntity();
				Header ceheader = entity.getContentEncoding();
				if (ceheader != null) {
					HeaderElement[] codecs = ceheader.getElements();
					for (int i = 0; i < codecs.length; i++) {
						if (codecs[i].getName().equalsIgnoreCase("gzip")) {
							response.setEntity(new GzipDecompressingEntity(response.getEntity()));
							return;
						}
					}
				}
			}
		});
	}

	/**
	 * 取得URL
	 * 
	 * @param requestEntity
	 * @param isURL
	 * @return
	 * @throws Exception
	 */
	public String getURL(RequestEntity requestEntity) throws Exception {

		mRequestEntity = requestEntity;
		if (mRequestEntity == null)
			return null;
		// 判断是什么方式请求

		URI uri = URIUtils.createURI(HTTP_SCHEME, HTTP_HOST, -1, HTTP_AGENT, URLEncodedUtils.format(fillGetParams(mRequestEntity), "UTF-8"), null);
		return uri.toString();

	}

	public AgentInputStream execute(RequestEntity requestEntity, boolean isUrl) throws Exception {
		mRequestEntity = requestEntity;
		if (mRequestEntity == null)
			return null;
		// 网络探测
		Apn.init();

		// 设置代理
		if (Apn.M_USE_PROXY) {
			HttpHost proxy = new HttpHost(Apn.M_APN_PROXY, Apn.M_APN_PORT);
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		} else {
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
		}

		// 判断是什么方式请求
		//URIUtils.
		
		UtilsLog.e("url", requestEntity.getUrl());
		mHttpRequest = new HttpGet(requestEntity.getUrl());

		// 填充 HTTP 头
		fillHeader(requestEntity);

		mHttpResponse = mHttpClient.execute(mHttpRequest);

		switch (mHttpResponse.getStatusLine().getStatusCode()) {
		case HttpStatus.SC_OK:
			// 抄录 inputstream, gzip 支持
			HttpEntity entity = mHttpResponse.getEntity();
			if (entity != null) {
				mEntityInputStream = entity.getContent();
				mInputStream = new AgentInputStream(mEntityInputStream);
			}
			return mInputStream;
		}
		return null;
	}

	@Override
	public AgentInputStream execute(RequestEntity requestEntity) throws Exception {
		mRequestEntity = requestEntity;
		if (mRequestEntity == null)
			return null;
		// 网络探测
		Apn.init();

		// 设置代理
		if (Apn.M_USE_PROXY) {
			HttpHost proxy = new HttpHost(Apn.M_APN_PROXY, Apn.M_APN_PORT);
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		} else {
			mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
		}

		// 判断是什么方式请求
		if (mRequestEntity.getMethod() == NetTask.METHOD_GET) {
			URI uri = URIUtils.createURI(HTTP_SCHEME, HTTP_HOST, -1, HTTP_AGENT, URLEncodedUtils.format(fillGetParams(mRequestEntity), "UTF-8"), null);
			UtilsLog.e("url", uri.toString());
			mHttpRequest = new HttpGet(uri);
		} else {
			URI uri = URIUtils.createURI(HTTP_SCHEME, HTTP_HOST, -1, HTTP_AGENT, null, null);
			UtilsLog.e("url", uri.toString());
			HttpPost httpPost = new HttpPost(uri);
			httpPost.setEntity(fillPostParams(mRequestEntity));
			mHttpRequest = httpPost;
		}

		// 填充 HTTP 头
		fillHeader(requestEntity);

		mHttpResponse = mHttpClient.execute(mHttpRequest);

		switch (mHttpResponse.getStatusLine().getStatusCode()) {
		case HttpStatus.SC_OK:
			// 抄录 inputstream, gzip 支持
			HttpEntity entity = mHttpResponse.getEntity();
			if (entity != null) {
				mEntityInputStream = entity.getContent();
				mInputStream = new AgentInputStream(mEntityInputStream);
			}
			return mInputStream;
		}
		return null;
	}

	/**
	 * 得到get方法的请求参数实体
	 * 
	 * @param entity
	 * @return
	 */
	private List<NameValuePair> fillGetParams(RequestEntity entity) {
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		Map<String, String> params = entity.getParams();
		Set<Entry<String, String>> set = params.entrySet();
		for (Map.Entry<String, String> entry : set) {
			if (!StringUtils.isNullOrEmpty(entry.getValue()))
				qparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		qparams.add(new BasicNameValuePair("wirelesscode", StringUtils.getMD5Str(URLEncodedUtils.format(qparams, "UTF-8") + MD5_CONSTANT)));
		return qparams;
	}

	/**
	 * 得到post方式的请求参数实体
	 * 
	 * @param entity
	 * @return
	 * @throws IOException
	 */
	private UrlEncodedFormEntity fillPostParams(RequestEntity entity) throws IOException {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		Map<String, String> params = entity.getParams();
		Set<Entry<String, String>> set = params.entrySet();
		for (Map.Entry<String, String> entry : set) {
			if (!StringUtils.isNullOrEmpty(entry.getValue()))
				formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		String wirelesscode = StringUtils.getMD5Str(entity.getParam("messagename") + MD5_CONSTANT);
		formparams.add(new BasicNameValuePair("wirelesscode", wirelesscode));
		return new UrlEncodedFormEntity(formparams, "UTF-8");
	}

	/**
	 */
	private void fillHeader(RequestEntity entity) {
		Map<String, String> headerMap = entity.getHeaders();
		for (Map.Entry<String, String> entry : headerMap.entrySet()) {
			mHttpRequest.setHeader(entry.getKey(), entry.getValue());
		}
		mHttpRequest.setHeader("version", Apn.version);// 版本号
		mHttpRequest.setHeader("connmode", Apn.getApnName(Apn.M_APN_TYPE));// 联网方式
		mHttpRequest.setHeader("imei", Apn.imei);// 手机串号
		mHttpRequest.setHeader("phoneNumber", Apn.phoneNumber);// 手机号码
		mHttpRequest.setHeader("posmode", "gps,wifi");// 定位方式
		mHttpRequest.setHeader("ispos", "" + Apn.ispos);// 是否定位成功
		mHttpRequest.setHeader("iscard", Apn.iscard);// 有无sim卡
		mHttpRequest.setHeader("company", Apn.APP_COMPANY);// 渠道号
	}

	public static void shutdown() {
		mHttpClient.getConnectionManager().shutdown();
	}

	@Override
	public void close() {
		if (mInputStream != null) {
			try {
				mInputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (mEntityInputStream != null) {
			try {
				mEntityInputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		abort();
		// 关闭过期连接
		mConnManager.closeExpiredConnections();
		// 可选地，关闭空闲超过30秒的连接
		mConnManager.closeIdleConnections(30, TimeUnit.SECONDS);
	}

	@Override
	public void abort() {
		if (mHttpRequest != null)
			mHttpRequest.abort();
	}

	/**
	 * @return
	 */
	public static HttpClient getHttpClient() {
		return mHttpClient;
	}

	static class GzipDecompressingEntity extends HttpEntityWrapper {
		public GzipDecompressingEntity(final HttpEntity entity) {
			super(entity);
		}

		@Override
		public InputStream getContent() throws IOException, IllegalStateException {
			// the wrapped entity's getContent() decides about repeatability
			InputStream wrappedin = wrappedEntity.getContent();
			return new GZIPInputStream(wrappedin);
		}

		@Override
		public long getContentLength() {
			// length of ungzipped content is not known
			return -1;
		}
	}
}
